'use strict'
import { View } from '../../component'
import style from './css.css'
class Canvas extends React.Component {
  static propTypes = {
    txDetail: PropTypes.object,
    state: PropTypes.number,
    getTXSDK: PropTypes.func,
    changeGameState: PropTypes.func,
    videosPos: PropTypes.number
  }
  state ={
    times: 3
  }
  timeFlag = null
  canvasMain = null
  canvasSlide = null
  _initSDKCallback = this._initSDKCallback.bind(this)
  _isReadyToShow = this._isReadyToShow.bind(this)
  _setTXSDK = this._setTXSDK.bind(this)
  _setTXSDK () {
    if (TXWawaVideo._isStart) {
      this._isReadyToShow()
      return
    }
    TXWawaVideo._isStart = true
    const { txDetail } = this.props
    const { sdkappid, accounttype, roomId, identifier, usersig, front, side, sig, ver } = txDetail
    const renderType = 0
    const listeners = (res) => { window.location.reload() }
    const opt = { sdkappid, accounttype, roomId, identifier, usersig, front, side, sig, ver, renderType, listeners }
    console.log('初始化SDK')
    TXWawaVideo.init(opt, this._initSDKCallback, (err) => {
      console.log(err)
      window.location.reload()
    })
  }
  _isReadyToShow () {
    TXWawaVideo.renderFront()
    // 倒计时三秒之后再开始
    this.timeFlag = setInterval(() => {
      const times = this.state.times - 1
      this.setState({ times })
      if (times === 0) {
        clearInterval(this.timeFlag)
        this.setState({ times: 3 })
        console.log('倒数' + times)
        if (this.props.state === 1) { this.props.changeGameState(2) }
      }
    }, 1000)
    this.props.changeGameState(1)
  }
  _initSDKCallback (res) {
    TXWawaVideo.renderVideo([this.canvasMain, this.canvasSlide], this._isReadyToShow)
  }
  componentDidMount () {
    this.props.getTXSDK(this._setTXSDK)
    TXWawaVideo._isStart = false
  }
  componentWillUnmount () {
    this.canvasMain = null
    this.canvasSlide = null
    this.props.getTXSDK(null)
    if (this.timeFlag) { clearInterval(this.timeFlag) }
    TXWawaVideo.destroy()
    TXWawaVideo._isStart = false
  }
  render () {
    const { videosPos, state } = this.props
    return (
      <View className={style.canvases} style={{ opacity: state >= 0 ? 1 : 0 }} >
        <View className={style.times } style={{ opacity: state === 1 ? 1 : 0 }} >
          <View className={style.timeTitle }>即将开始</View>
          <View className={style.timeText }>{this.state.times}s</View>
        </View>
        <canvas style={{ opacity: (videosPos === 0 && state === 2) ? 1 : 0 }} className={style.canvas} width="480" height="640" ref={(res) => { this.canvasMain = res }}></canvas>
        <canvas style={{ opacity: (videosPos === 1 && state === 2) ? 1 : 0 }} className={style.canvas} width="480" height="640" ref={(res) => { this.canvasSlide = res }}></canvas>
      </View>
    )
  }
}

export default Canvas
